goog.provide('otq.StayInListPlugin');

goog.require('goog.dom.TagName');
goog.require('goog.editor.Command');
goog.require('goog.editor.Plugin');
goog.require('goog.events.KeyCodes');

/**
 * Plugin to intercept some of the worse things you can do to mangle a list
 * in trogedit. Far from complete.
 *
 * Relies on an ugly execCommandInternal intercept system. This plugin claims
 * to handle INDENT and OUTDENT. If it determines they are reasonable, it
 * passes the commands onto the BasicTextFormatter plugin.
 *
 * @constructor
 * @param {goog.editor.plugins.BasicTextFormatter} btf BasicTextFormatter
 * @extends {goog.editor.Plugin}
 */
otq.StayInListPlugin = function(btf) {
  goog.editor.Plugin.call(this);
	
	/** @type {goog.editor.plugins.BasicTextFormatter} */
	this.btf_ = btf;
};
goog.inherits(otq.StayInListPlugin, goog.editor.Plugin);

/** @override */
otq.StayInListPlugin.prototype.getTrogClassId = function() {
  return 'StayInListPlugin';
};

/** @override */
otq.StayInListPlugin.prototype.isSupportedCommand = function(c) {
	switch (c) {
		case goog.editor.Command.OUTDENT:
		case goog.editor.Command.INDENT:
			return true;
		default:
			return false;
	}
}

otq.StayInListPlugin.prototype.listDepth_ = function(elem) {
	var d = 0;
	for (; elem != null; elem = elem.parentNode) {
		if (elem.tagName == 'UL') {
			d++;
		}
	}
	return d;
};

/** @override */
otq.StayInListPlugin.prototype.execCommandInternal = function(c) {
	window.console.log("execCommandInternal: " + c);

	var container = this.fieldObject.getRange().getContainerElement();
	var depth = this.listDepth_(container);
	window.console.log("depth: " + depth);

	switch (c) {
		case goog.editor.Command.OUTDENT:
			if (depth > 1) {
				this.btf_.execCommandInternal(c);
			}
			break;
		case goog.editor.Command.INDENT:
			if (depth < 2) {
				this.btf_.execCommandInternal(c);
			}
			break;
		default:
			this.btf_.execCommandInternal(c);
	}
};

/**
 * Extra editor limits by capturing certain key combinations.
 * @override
 */
otq.StayInListPlugin.prototype.handleKeyboardShortcut = function(e, key, mod) {
	if (e.keyCode != goog.events.KeyCodes.ENTER) {
		return false;
	}

	if (e.shiftKey) {
		// No newlines in objectives and key results.
		return true;
	}

	var range = this.fieldObject.getRange();
	var container = range.getContainerElement();
	if (container.tagName == goog.dom.TagName.LI) {
		if (container.innerText.trim() == "") {
			// No escaping from lists by pressing enter on an empty item.
			return true;
		}
	}
	return false;
};
